# python 3.8

import random
import time

from paho.mqtt import client as mqtt_client

# from device import  ProductKey, DeviceName, DeviceSecret 

DeviceName = 'FlocPannel'
DeviceSecret = 'fadsfdsaf'

# broker = '106.14.208.205'
broker = 'mq.flocwise.cn'
port = 1883
topic = "python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = DeviceName
password = DeviceSecret

TAKE_PICTURE_ACTION = False

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
            listenTopic = f'/Dr.Doctor/{DeviceName}/uploadImg/#'
            subscribe(client, listenTopic)
            # sendTopic = f'/Dr.Doctor/{DeviceName}/imgUploaded'            
            # publish(client, sendTopic)
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    # client.tls_set(ca_certs='./server-ca.crt')
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client, topic):
    def on_message(client, userdata, msg):
        global TAKE_PICTURE_ACTION
        try:
            print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")        
            print('msg:', msg.topic)        
            if msg.topic == '/Dr.Doctor/Floc024/uploadImg':
                TAKE_PICTURE_ACTION = True
            else:
                print('ignor')
        except Exception as e:
            print(e)

    client.subscribe(topic)
    client.on_message = on_message

def mqttUploadImage(filename):
    f = open(filename, "rb")
    fileContent = f.read()
    byteArr = bytes(fileContent)
    sendTopic = f'/Dr.Doctor/{DeviceName}/imgUploaded'
    publish(client, sendTopic, payload=byteArr)
    print('完成图片上传')
    #publishing the message with bytearr as the payload and IMAGE as topic

def publish(client, topic, payload=''):
        msg = payload
        result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"发送成功 to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")

    # publish(client)

client = connect_mqtt()
client.loop_start()


# if __name__ == '__main__':
#     run()